package com.mk.magic_c.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.magic_c.dto.DiscussPostHomeVo;
import com.mk.magic_c.dto.PaginationParam;
import com.mk.magic_c.service.DiscussPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/10/2 6:58 下午
 * @desc 首页
 */
@Slf4j
@Controller
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;

    @GetMapping({"/", "/index", "/index.html"})
    public String index(HttpServletRequest request,
                        @RequestParam(name = "current", required = false, defaultValue = "1") long current,
                        @RequestParam(name = "size", required = false, defaultValue = "10") long size,
                        Model model) {
        Page<DiscussPostHomeVo> discussPostHomeVoPage = discussPostService.listHomePost(current, size);
        // 数据集合
        List<DiscussPostHomeVo> posts = discussPostHomeVoPage.getRecords();
        // 分页参数
        PaginationParam<DiscussPostHomeVo> page = PaginationParam.restPage(discussPostHomeVoPage);
        // 设置请求路径
        page.setPath(request.getServletPath());
        log.debug("ServletPath -> " + request.getServletPath());
        model.addAttribute("posts", posts);
        model.addAttribute("page", page);
        return "index";
    }
}
